<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="form" :model="search" label-width="80px" :inline="true">
        <el-form-item label="点位搜索:">
          <el-input v-model="search.name" clearable placeholder="请输入" size="medium" />
        </el-form-item>
        <el-form-item label="区域搜索:">
          <el-select v-model="search.regionId" clearable placeholder="请选择">
            <el-option
              v-for="item in regionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="medium"
            class="my-primary1"
            icon="el-icon-search"
            @click="query"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="result">
      <el-row type="flex" class="operation">
        <el-button
          type="primary"
          class="my-primary2"
          icon="el-icon-circle-plus-outline"
          @click="showAdd('add')"
        >新建</el-button>
      </el-row>
      <el-table
        :data="tableData"
        style="width: 100%"
        empty-text="暂无数据"
        fit
        highlight-current-row
        :cell-style="{
          height: '44px',
          padding: '2px 0px',
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
        :header-cell-style="{
          lineHeight: 1.15,
          padding: '10px 0px 9px',
          background: 'rgb(243, 246, 251)',
          fontWeight: 500,
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
      >
        <el-table-column
          type="index"
          :index="(index) => (search.pageIndex - 1) * 10 + (index + 1)"
          label="序号"
          width="80px"
        />
        <el-table-column prop="name" label="点位名称" />
        <el-table-column prop="region.name" label="所在区域" />
        <el-table-column prop="businessType.name" label="商圈类型" />
        <el-table-column prop="ownerName" label="合作商" />
        <el-table-column label="详细地址">
          <template v-slot="{row}">
            {{ row.addr.substring(row.addr.lastIndexOf("-")+1) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="{ row }">
            <el-button type="text" class="el-button--primary-text" @click.native="showNodeInfo(row.id)">
              查看详情
            </el-button>
            <el-button type="text" class="el-button--primary-text" @click.native="recreate(row)">
              修改
            </el-button>
            <el-button type="text" class="el-button--danger-text" @click.native="delNode(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          layout="slot,prev,next"
          :current-page.sync="search.pageIndex"
          :total="totalCount"
          :page-size="search.pageSize"
          prev-text="上一页"
          next-text="下一页"
          @current-change="nodeSearch"
        >
          <template order="-1">
            <span
              class="el-pagination__total"
            >共{{ totalCount }}条记录 第 {{ search.pageIndex }}/{{
              totalPage
            }}
              页</span>
          </template>
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="新增点位"
      :visible.sync="addDialog"
      width="630px"
      top="15vh"
      @close="addClose"
    >
      <el-form
        ref="add"
        :model="addForm"
        :rules="addRules"
        label-width="140px"
        size="medium"
      >
        <el-form-item label="点位名称：" prop="name">
          <el-input
            v-model="addForm.name"
            autocomplete="off"
            placeholder="请输入"
            style="width: 396px"
            maxlength="15"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="所在区域:" prop="regionId">
          <el-select v-model="addForm.regionId" clearable placeholder="请选择" style="width:396px">
            <el-option
              v-for="item in regionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属商圈:" prop="businessId">
          <el-select v-model="addForm.businessId" clearable placeholder="请选择" style="width:396px">
            <el-option
              v-for="item in businessList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="归属合作商:" prop="ownerId">
          <el-select v-model="addForm.ownerId" clearable placeholder="请选择" style="width:396px">
            <el-option
              v-for="item in partnerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址:" prop="areaCode">
          <el-cascader
            v-model="city"
            :options="$store.state.user.city"
            :props="props"
            placeholder="请选择"
            clearable
            style="width:396px"
            @change="handleCascaderChange"
          />
        </el-form-item>
        <el-form-item prop="addr">
          <el-input
            v-model="addr"
            type="textarea"
            :rows="4"
            placeholder="请输入详细地址"
            style="width: 396px"
            maxlength="60"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="16">
              <el-button class="my-secondary" @click="addClose">取消</el-button>
              <el-button
                type="primary"
                class="my-primary2"
                @click="addSubmit"
              >确认</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="点位详情"
      :visible.sync="nodeInfoDialog"
      width="630px"
      @close="nodeInfoClose"
    >
      <el-table
        :data="nodeInfo"
        style="width: 552px; margin:0 auto;"
        empty-text="暂无数据"
        fit
        highlight-current-row
        :cell-style="{
          height: '44px',
          padding: '2px 0px',
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
        :header-cell-style="{
          lineHeight: 1.15,
          padding: '10px 0px 9px',
          background: 'rgb(243, 246, 251)',
          fontWeight: 500,
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
      >
        <el-table-column
          type="index"
          :index="(index) => index + 1"
          label="序号"
          width="80px"
        />
        <el-table-column prop="innerCode" label="机器编号" />
        <el-table-column label="设备状态">
          <template v-slot="{row}">
            {{ row.vmStatus === 0 ? '未投放': row.vmStatus === 1 ? '运营' : '撤机' }}
          </template>
        </el-table-column>
        <el-table-column label="最后一次供货时间">
          <template v-slot="{row}">
            {{ formattedDate(row.lastSupplyTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { searchRegionList, addNode, searchNode, getBusinessList, getNodeInfo, delNode, updateNode } from '@/api/vm'
import { searchPartner } from '@/api/user'
export default {
  data() {
    return {
      search: {
        name: null,
        regionId: null,
        pageIndex: 1,
        pageSize: 10
      },
      tableData: [],
      totalCount: 0,
      totalPage: 0,
      addDialog: false,
      addForm: {
        addr: '',
        areaCode: '',
        businessId: '',
        createUserId: this.$store.getters.userId,
        name: '',
        ownerId: '',
        ownerName: '',
        regionId: ''
      },
      addRules: {
        addr: [{ required: true, message: '请输入', trigger: 'change' }],
        areaCode: [{ required: true, message: '请选择', trigger: 'change' }],
        businessId: [{ required: true, message: '请选择', trigger: 'change' }],
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        ownerId: [{ required: true, message: '请选择', trigger: 'change' }],
        regionId: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      nodeInfoDialog: false,
      nodeInfo: {},
      type: '',
      regionList: [],
      businessList: [],
      partnerList: [],
      nodeList: [],
      props: {
        value: 'adcode', // 关联字段为区域id
        label: 'name',
        children: 'districts'
      },
      addr: '',
      current: {},
      city: null
    }
  },
  async created() {
    await this.nodeSearch()
    this.searchRegionList()
  },
  methods: {
    query() {
      this.search.pageIndex = 1
      this.nodeSearch()
    },
    async searchRegionList() {
      const res = await searchRegionList({ pageIndex: 1, pageSize: 100000 })
      this.regionList = res.currentPageRecords
    },
    async nodeSearch() {
      const { currentPageRecords, totalCount, totalPage } = await searchNode({
        ...this.search
      })
      this.totalCount = parseInt(totalCount)
      this.totalPage = totalPage
      this.tableData = currentPageRecords
    },
    formattedDate(date) {
      const currentDate = new Date(date)
      const year = currentDate.getFullYear()
      const month = ('0' + (currentDate.getMonth() + 1)).slice(-2)
      const day = ('0' + currentDate.getDate()).slice(-2)
      const hours = ('0' + currentDate.getHours()).slice(-2)
      const minutes = ('0' + currentDate.getMinutes()).slice(-2)
      const seconds = ('0' + currentDate.getSeconds()).slice(-2)
      return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
    },
    async showAdd(type) {
      this.addDialog = true
      this.type = type
      this.businessList = await getBusinessList()
      const { currentPageRecords } = await searchPartner({ pageIndex: 1, pageSize: 100000 })
      this.partnerList = currentPageRecords
      this.$store.dispatch('user/loadData')
    },
    addClose() {
      this.addDialog = false
      this.$refs.add.resetFields()
      this.addForm = {
        addr: '',
        areaCode: '',
        businessId: '',
        createUserId: this.$store.getters.userId,
        name: '',
        ownerId: '',
        ownerName: '',
        regionId: ''
      }
      this.addr = ''
      this.city = null
    },
    async addSubmit() {
      this.$refs.add.validate(async(isOK) => {
        if (isOK) {
          if (this.type === 'add') {
            this.addForm.ownerName = this.partnerList.find(item => item.id === this.addForm.ownerId).name
            this.addForm.addr += this.addr
            this.addForm.areaCode = this.city[this.city.length - 1]
            await addNode({ ...this.addForm })
          } else {
            await updateNode({ ...this.addForm, id: this.current.id })
          }
          this.addClose()
          this.nodeSearch()
        }
      })
    },
    handleCascaderChange(selectedValues) {
      // 获取最后一级选中值的value和label
      const selectedValue = selectedValues[selectedValues.length - 1]
      this.addForm.areaCode = selectedValue
      this.addForm.addr = ''
      selectedValues.forEach(item => {
        const selectedLabel = this.getLabelByValue(item)
        this.addForm.addr += selectedLabel + '-'
      })
    },
    getLabelByValue(adcode) {
      // 根据value从options中获取对应的label
      const search = (options, adcode) => {
        for (let i = 0; i < options.length; i++) {
          if (options[i].adcode === adcode) {
            return options[i].name
          } else if (options[i].districts) {
            const result = search(options[i].districts, adcode)
            if (result) {
              return result
            }
          }
        }
      }
      return search(this.$store.state.user.city, adcode)
    },
    async showNodeInfo(id) {
      this.nodeInfoDialog = true
      this.nodeInfo = await getNodeInfo(id)
    },
    nodeInfoClose() {
      this.nodeInfoDialog = false
    },
    async recreate(row) {
      this.current = { ...row }
      this.addForm = {
        addr: row.addr,
        areaCode: row.areaCode,
        businessId: row.businessId,
        name: row.name,
        ownerId: row.ownerId,
        regionId: row.regionId,
        createUserId: row.createUserId,
        ownerName: row.ownerName
      }
      this.addr = row.addr.substring(row.addr.lastIndexOf('-') + 1)
      this.city = row.areaCode
      this.showAdd('edit')
      this.nodeInfoClose()
    },
    async delNode(id) {
      this.$confirm('您确定删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delNode(id)
        if (this.tableData.length === 1) this.search.pageIndex--
        this.nodeSearch()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/common.scss'
</style>
